package com.ac.api.qms_inspection_record.controller;

import com.ac.api.qms_quality_standard.entity.QmsQualityStandard;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.base.annotation.SysLog;
import org.springframework.web.bind.annotation.RestController;
import com.base.helper.BaseController;
import com.base.helper.Result;
import com.ac.api.qms_inspection_record.entity.QmsInspectionRecord;
import com.ac.api.qms_inspection_record.service.QmsInspectionRecordService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ry
 * @since 2025-06-16
 */
@Api(tags = "QmsInspectionRecord")
@RestController
@RequestMapping("/qmsInspectionRecord")
public class QmsInspectionRecordController extends BaseController {

        private static final Logger       LOG = LoggerFactory.getLogger(QmsInspectionRecordController.class);
        @Autowired
        private              QmsInspectionRecordService entityService;

        @SysLog(action = "findByPage", value = "分页查询质检记录")
        @ApiOperation(value = "分页查询质检记录", notes = "分页查询质检记录")
        @GetMapping(value = "/findByPage")
        @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
        public Result<IPage<QmsInspectionRecord>> findByPage(final QmsInspectionRecord example, final Page page) {
            IPage<QmsInspectionRecord>        records    = entityService.page(example,page);
            return new Result(true, records);
        }

        @SysLog(action = "delete", value = "删除质检记录")
        @ApiOperation(value = "删除质检记录")
        @DeleteMapping(value = "/delete")
        @ApiImplicitParam(name = "id", value = "记录ID", required = true)
        public Result delete(@RequestParam Integer id) {
            try {
                entityService.removeById(id);
                return new Result(true, "成功删除质检记录", null);
            } catch (DataIntegrityViolationException e) {
                LOG.error("删除质检记录失败", e);
                return new Result(false, "删除质检记录失败", "该质检记录不能删除，存在其他关联数据");
            } catch (Exception e) {
                LOG.error("删除质检记录失败", e);
                return new Result(false, "删除质检记录失败", e.getMessage());
            }
        }

        @SysLog(action = "one", value = "查询单个质检记录")
        @ApiOperation(value = "查询单个质检记录")
        @GetMapping(value = "/check")
        @ApiImplicitParam(name = "id", value = "记录ID", required = true)
        public Result one(@RequestParam Integer id) {
            try {
                QmsInspectionRecord entity = entityService.getById(id);
                return new Result(true, entity);
            } catch (Exception e) {
                LOG.error("查询单个质检记录失败", e);
                return new Result(false, new QmsInspectionRecord());
            }
        }

    @SysLog(action = "search", value = "搜索质检记录")
    @ApiOperation(value = "搜索质检记录")
    @GetMapping(value = "/search")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "batchNo", value = "关联产品批次", required = false),
            @ApiImplicitParam(name = "result", value = "质检结果", required = false)
    })
    public Result search(
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String result,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        try {
            Page<QmsInspectionRecord> page = new Page<>(pageNum, pageSize);
            QueryWrapper<QmsInspectionRecord> queryWrapper = new QueryWrapper<>();

            if (StringUtils.isNotBlank(batchNo)) {
                queryWrapper.like("batch_no", batchNo.trim());
            }

            if (StringUtils.isNotBlank(result)) {
                queryWrapper.eq("result", result.trim());
            }

            IPage<QmsInspectionRecord> resultPage = entityService.page(page, queryWrapper);

            // 检查是否有结果
            if (resultPage == null || resultPage.getRecords() == null || resultPage.getRecords().isEmpty()) {
                return new Result(true, "无结果");
            }

            return new Result(true, resultPage);
        } catch (Exception e) {
            LOG.error("搜索质检记录失败", e);
            return new Result(false, "查询失败，请稍后重试");
        }
    }
        @SysLog(action = "add", value = "添加质检记录")
        @ApiOperation(value = "添加质检记录")
        @PostMapping(value = "/add")
        public Result add(@Valid @RequestBody final QmsInspectionRecord entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "保存质检记录失败", errorMsg, map);
                } else {
                    entityService.save(entity);
                    return new Result(true, "成功保存质检记录", null);
                }
            } catch (Exception e) {
                LOG.error("添加质检记录失败", e);
                return new Result(false, "保存质检记录失败", e.getMessage());
            }
        }

        @SysLog(action = "update", value = "修改质检记录")
        @ApiOperation(value = "修改质检记录")
        @PostMapping(value = "/update")
        public Result update(@Valid @RequestBody final QmsInspectionRecord entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "修改记录失败", errorMsg, map);
                } else {
                    if (null == entity.getId()) {
                         throw new RuntimeException("id不能为空");
                    }
                    entityService.updateById(entity);
                    return new Result(true, "成功修改质检记录", null);
                }
            } catch (Exception e) {
                LOG.error("修改记录失败", e);
                return new Result(false, "修改记录失败", e.getMessage());
            }
        }

        @ApiOperation(value = "全部质检记录")
        @GetMapping(value = "/all")
        public Result<List<QmsInspectionRecord>> all(QmsInspectionRecord example) {
            List<QmsInspectionRecord> entitys = entityService.list(example);
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }

}

